<?php
namespace app\services;

use app\utils\Functions as F;
use app\utils\Upload as Up;

class PackageSyncService extends ReportService {

    public $packageListMatrix = [
        'name' => ['type', '$v==0 && $v="Package";
                            $v==1 && $v=\Yii::t("package", "Banner Package");
                            $v==2 && $v=\Yii::t("package", "Video Package");
                            $v==4 && $v=\Yii::t("package", "Mobile Package");
                            return $v;'],
        'type' => ['type', '$v==0 && $v="package";
                            $v==1 && $v="banner";
                            $v==2 && $v="video";
                            $v==4 && $v="mobile";
                            return $v;'],
        'recentUpdate' => 'begin',
        'modifiedDate' => 'end',
        'operate' => 'update',
    ];

    public function updatePackage() {
        $url = \Yii::$app->params['package']['update'];
        try {
            $result = file_get_contents($url);
        } catch (\Exception $e) {
            return $this->NG($this->t('package', 'Syncronization failed!'));
        }
        switch ($result) {
            case 'ING':
                return $this->OK($this->t('package', 'Package is updating!'));
                break;
            case 'OK':
                return $this->OK($this->t('package', 'Package is updated!'));
                break;
            case 'NG':
                return $this->NG($this->t('package', 'Update failed!'));
                break;
            default:
                return $this->NG($this->t('package', 'Update failed!'));
                break;
        }
    }

    public function getPackageScheduleList() {
        $sql = "select p.id, p.type, p.begin, p.end
                from {{%package_schedule}} as p
                inner join (
                    select type, max(id) as mid
                    from {{%package_schedule}}
                    group by type
                ) at on at.type = p.type and p.id = at.mid";
        $list = $this->query($sql);
        $data = $this->fieldsMap($this->packageListMatrix, $list);
        return $data;
    }
}//end

